package com.yuan.controller;

import com.yuan.bean.SysUser;
import com.yuan.service.AsyncService;
import com.yuan.service.SysUserService;
import com.yuan.untils.ListUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CountDownLatch;

/**
 * @Author：YuanHaHa
 * @Date：2024/7/4 15:15
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class SysUserController {

    @Autowired
    private SysUserService userService;
    @Autowired
    private AsyncService asyncService;

    @GetMapping("/add")
    public String addUser(){
        log.info("开始批量操作.......");
        Random random = new Random();
        ArrayList<SysUser> userList = new ArrayList<SysUser>();
        for (int i = 0; i < 1000000; i++) {
            SysUser user = new SysUser();
            user.setUserName("老王");
            user.setUserAge(random.nextInt(100));
            userList.add(user);
        }

        long startTime = System.currentTimeMillis();
        // 改用异步导入
        List<List<SysUser>> userListPage = ListUtils.splitsListPage(userList, 100);
        // 同步工具对象
        CountDownLatch countDownLatch = new CountDownLatch(userListPage.size());
//        userService.saveBatch(userList);
        for (List<SysUser> sysUsers : userListPage) {
           asyncService.executorAsync(sysUsers, userService, countDownLatch);
        }

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            log.error("阻塞"+e.getMessage());
        }
        long endTime = System.currentTimeMillis();
        log.info("总共耗时："+(endTime - startTime)/ 1000 + " s");
        return "任务执行完成！";
    }

}
